import {
  ViewController,
  IGridViewEvent,
  IGridViewState,
  MDViewEngine,
  IGridController,
  SysUIActionTag,
} from '@ibiz-template/runtime';
import { IAppDEGridView } from '@ibiz/model-core';

export class GridViewEngine extends MDViewEngine {
  protected declare view: ViewController<
    IAppDEGridView,
    IGridViewState,
    IGridViewEvent
  >;

  // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
  async call(key: string, args: any): Promise<IData | null | undefined> {
    if (key === SysUIActionTag.NEW_ROW) {
      this.grid.newRow();
      return null;
    }
    if (key === SysUIActionTag.TOGGLE_ROW_EDIT) {
      this.grid.toggleRowEdit();
      return null;
    }
    if (key === SysUIActionTag.SAVE_ROW) {
      this.grid.save(args.data[0]);
      return null;
    }
    if (key === SysUIActionTag.SAVE) {
      this.grid.saveAll();
      return null;
    }

    return super.call(key, args);
  }

  get grid(): IGridController {
    return this.view.getController('grid') as IGridController;
  }

  async onCreated(): Promise<void> {
    super.onCreated();
    const { model } = this.view;
    if (!this.view.slotProps.grid) {
      this.view.slotProps.grid = {};
    }
    this.view.slotProps.grid.mdctrlActiveMode = model.gridRowActiveMode!;
    this.view.slotProps.grid.rowEditOpen = model.rowEditDefault!;
  }
}
